/*****
 * 选择标签组件
 */
import { useEffect, useMemo, useState, useRef } from "react";
import CommonModal from "../CommonModal";
import CommonLoading from "../CommonLoading";
import { Checkbox, Button, Typography, Space, Input, Row, Col, Form } from "antd";
import { find, groupBy } from "lodash";
import { queryStoreList } from "./service";
import styles from "./index.module.less";
import ShopIcons from "./ShopIcons";
import { platformTypeName } from "@/utils/config";

const CheckboxGroup = Checkbox.Group;

const renderTitle = key => {
	return (
		<div style={{ display: "flex", width: "100%", alignItems: "center" }}>
			<ShopIcons type={key} />
			<Typography style={{ marginLeft: 8 }}>{platformTypeName[key]}</Typography>
		</div>
	);
};

const SelectShop = props => {
	const { title = "选择平台店铺", storeIds = [], selectShops, handleOk, handleCancel } = props;

	//店铺列表
	const [storeList, setStoreList] = useState([]);

	//选择标签
	const [selectStore, setSelectStore] = useState({});

	const [indeterminate, setIndeterminate] = useState({});
	const [checkAll, setCheckAll] = useState({});

	const [value, setValue] = useState("");

	const [loading, setLoading] = useState(false);

	const inputRef = useRef(null);

	//真正用于渲染的标签列表
	const realData = useMemo(() => {
		if (storeList.length > 0) {
			return groupBy(storeList, "type");
		} else {
			return {};
		}
	}, [storeList]);

	//初始化获取店铺列表
	useEffect(() => {
		getStoreList();
	}, []);

	useEffect(() => {
		const list = [];
		if (selectShops.length && storeList.length) {
			selectShops.forEach(id => {
				const item = find(storeList, ["id", id]);
                if(item) {
                    list.push(item);
                }
			});
			const originalObj = groupBy(list, "type");
			const transformedObj = Object.fromEntries(
				Object.entries(originalObj).map(([key, value]) => [key, value.map(({ id }) => id)])
			);
			let indeterminateObj = {},
				checkAlObj = {};
			for (let key in transformedObj) {
				if (key || key == 0) {
					if (transformedObj[key].length == realData[key].length) {
						//全选
						checkAlObj = Object.assign(checkAlObj, { [key]: true });
					} else {
						//部分选择
						indeterminateObj = Object.assign(indeterminateObj, { [key]: true });
					}
				}
			}
			setSelectStore(transformedObj);
			setIndeterminate(indeterminateObj);
			setCheckAll(checkAlObj);
		}
	}, [selectShops, storeList]);

	//获取d店铺列表
	const getStoreList = async val => {
		setLoading(true);
		const { success, data = {} } = await queryStoreList({
			...val,
			current: 1,
			size: 500
		});
		setLoading(false);
		const { records = [] } = data;
		const arr = records.map(item => {
			return {
				...item,
				isCheck: false
			};
		});
		if (success) {
            if(storeIds.length) {
               const list = arr.filter(item => !storeIds.includes(item.id));
			   setStoreList(list);
            } else {
                setStoreList(arr);
            }
		}
	};

	//点击搜索
	const handleSearch = () => {
		if (inputRef.current) {
			getStoreList({
				storeName: inputRef.current.input.value
			});
		}
	};

	//点击重制
	const handleReset = () => {
		if (inputRef.current) {
			setValue("");
			inputRef.current.input.value = "";
		}
		getStoreList({
			storeName: ""
		});
	};

	//选择变更
	const onChange = (list, key) => {
		setSelectStore({
			...selectStore,
			[key]: list
		});
		setIndeterminate({
			...indeterminate,
			[key]: !!list.length && list.length < realData[key].length
		});
		setCheckAll({
			...checkAll,
			[key]: list.length === realData[key].length
		});
	};

	//全选事件
	const onCheckAllChange = (e, key) => {
		setSelectStore({
			...selectStore,
			[key]: e.target.checked ? realData[key].map(v => v.id) : []
		});
		setIndeterminate({
			...indeterminate,
			[key]: false
		});
		setCheckAll({
			...checkAll,
			[key]: e.target.checked
		});
	};

	//店铺组
	const renderStore = () => {
		return (
			<div>
				<Row style={{ marginBottom: "24px" }} gutter={14}>
					<Col flex="auto">
						<Input value={value} onChange={e => setValue(e.target.value)} ref={inputRef} placeholder="请输入平台/店铺" />
					</Col>
					<Col>
						<Space>
							<Button
								type="primary"
								onClick={() => {
									handleSearch();
								}}
							>
								搜索
							</Button>
							<Button
								onClick={() => {
									handleReset();
								}}
								style={{ marginRight: 8 }}
							>
								重置
							</Button>
						</Space>
					</Col>
				</Row>

				{Object.keys(realData).map(key => (
					<div className={styles.checkItem} key={key}>
						<Checkbox indeterminate={indeterminate[key]} onChange={e => onCheckAllChange(e, key)} checked={checkAll[key]}>
							{renderTitle(key)}
						</Checkbox>
						<CheckboxGroup className={styles.checkWrap} value={selectStore[key]} onChange={e => onChange(e, key)}>
							{realData[key].map(v => {
								return (
									<Checkbox className={styles.checkBox} value={v.id} key={v.id}>
										{v.systemStoreName ? v.systemStoreName : v.storeName}
									</Checkbox>
								);
							})}
						</CheckboxGroup>
					</div>
				))}
			</div>
		);
	};

	//点击确定
	const onOk = () => {
		const list = [],
			arr = [].concat(...Object.values(selectStore).flat());
		arr.forEach(id => {
			const item = find(storeList, ["id", id]);
			list.push(item);
		});
		handleOk(list);
	};

	//点击取消
	const onCancel = () => {
		handleCancel();
	};

	return (
		<CommonModal
			title={title}
			open={true}
			width="600px"
			onCancel={onCancel}
			footer={
				<div>
					<Button onClick={onCancel}>取消</Button>
					<Button onClick={onOk} type="primary">
						确定
					</Button>
				</div>
			}
		>
			{renderStore()}
			<CommonLoading loading={loading} />
		</CommonModal>
	);
};

export default SelectShop;
